/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * BaseRemindTaskService
 * 提醒任务
 * 修改纪录
 * 2020-12-01 版本：1.0 zhanglongfei 创建。
 *
 * @version 版本：1.0
 * @author 作者：zhanglongfei
 * 创建日期：2020-12-01
 */
package com.topscomm.base.service.impl;

import java.io.IOException;
import java.util.*;

import com.topscomm.cbo.pojo.CboMessageMailEntity;
import com.topscomm.cbo.service.ICboMessageMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;

import com.topscomm.base.BaseSystemConst.NoticeTypeEnum;
import com.topscomm.base.pojo.BaseRemindTaskEntity;
import com.topscomm.base.service.IBaseRemindTaskService;
import com.topscomm.base.service.impl.auto.BaseRemindTaskServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboMessageAppEntity;
import com.topscomm.cbo.pojo.CboMessageSysEntity;
import com.topscomm.cbo.pojo.CboSysParamEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.ICboSysParamService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;

@Service(value = "baseRemindTaskService")
@Scope(value = "singleton")
public class BaseRemindTaskService extends BaseRemindTaskServiceAuto implements IBaseRemindTaskService {
	@Autowired
	private IBaseRemindTaskService baseRemindTaskService;
	@Autowired
	private ICboSysParamService cboSysParamService;
	@Autowired
	private ICboMessageAppService cboMessageAppService;
	@Autowired
	private ICboMessageSysService cboMessageSysService;
	@Autowired
	private ICboMessageMailService cboMessageMailService;
	@Value("${system.name}")
	private  String systemName;

	/**
	 * @description: 发送提醒消息
	 * @param paraMap
	 * @author: maxiaodong
	 * @date: 2020年12月10日上午10:05:23
	 * @modify:
	 */
	@Override
	public void sendRemindMessage(Map<String, Object> paraMap) {
		this.insertRemindTask(null, null);
	}

	/**
	 * @description: 将要发送的消息插入到BaseRemindTask表
	 * @param messageInfo
	 * @param paraMap
	 * @author: maxiaodong
	 * @date: 2020年12月10日下午1:55:15
	 * @modify:
	 */
	private void insertRemindTask(Map<String, Object> messageInfo, Map<String, Object> paraMap) {
		// 测试代码
		BaseRemindTaskEntity baseRemindTaskEntity = new BaseRemindTaskEntity();
		baseRemindTaskEntity.setContent("content");
		baseRemindTaskEntity.setNoticetype("app");
		baseRemindTaskEntity.setUsercode("9921");
		baseRemindTaskEntity.setUserid(1234567890);
		baseRemindTaskEntity.setUsername("马晓东");
		baseRemindTaskEntity.setSubject("subject");
		baseRemindTaskEntity.setSourceid("sourceid");
		baseRemindTaskEntity.setSourcetype("sourcetype");
		baseRemindTaskEntity.setRemindtime(new Date());
		baseRemindTaskEntity.setCreateuser(1234567890);
		baseRemindTaskService.insert(baseRemindTaskEntity);
	}

	/**
	 * @description: 根据定时任务发送消息
	 * @author: maxiaodong
	 * @date: 2020年12月10日下午3:50:41
	 * @modify:
	 */
	@Override
	public void taskToMessage() {
		CboSysParamEntity cboSysParamEntity = this.cboSysParamService.queryObjectByWhere("code='RemindCheckTaskLastRunTime'");
		String remindCheckTaskLastRunTime = cboSysParamEntity.getParamvalue();
		// 获取remindtime从上次检查时间到现在时间的所有Task的记录
		Date currenTime = new Date();
		String timeNowString = DateUtil.dateToString(currenTime, "yyyy-MM-dd HH:mm:ss");
		try {
			String timeNowStringLong = SQLAdapter.toDateLong(timeNowString);
			List<BaseRemindTaskEntity> baseRemindTaskEntityList = null;
			Calendar calendar = Calendar.getInstance();
			String remindCheckTaskLastRunEarlierTimeLong = null;
			if (remindCheckTaskLastRunTime == null || remindCheckTaskLastRunTime.equals("")) {
				// 系统首次运行
				calendar.setTime(currenTime);
				// 当前时间提前5分钟，解决立即发送的问题
				calendar.add(Calendar.MINUTE, -5);
				Date remindCheckTaskLastRunEarlierTime = calendar.getTime();
				remindCheckTaskLastRunEarlierTimeLong = SQLAdapter.toDateLong(DateUtil.dateToString(remindCheckTaskLastRunEarlierTime, "yyyy-MM-dd HH:mm:ss"));
			} else {
				// 系统非首次运行
				Date remindCheckTaskLastRunTimeDate = DateUtil.stringToDate(remindCheckTaskLastRunTime);
				calendar.setTime(remindCheckTaskLastRunTimeDate);
				// 上次检查时间提前5分钟，解决立即发送的问题
				calendar.add(Calendar.MINUTE, -5);
				Date remindCheckTaskLastRunEarlierTime = calendar.getTime();
				remindCheckTaskLastRunEarlierTimeLong = SQLAdapter
						.toDateLong(DateUtil.dateToString(remindCheckTaskLastRunEarlierTime, "yyyy-MM-dd HH:mm:ss"));
			}
			// 查询时间段内的消息
			StringBufferProxy queryTaskSql = new StringBufferProxy();
			queryTaskSql.appendSingle("( (state=0 or state is null) )");
			baseRemindTaskEntityList = this.baseRemindTaskService.queryByWhere(queryTaskSql.toString());
			// 遍历记录，如果记录不在config表则删除，如果在config表则发出。state改为1
			//app推送、消息数据
			List<BasicEntity> baseRemindTaskEntityAppRemindList = new ArrayList<>();
			//邮箱数据
			List<BasicEntity> baseRemindTaskEntityEmailRemindList = new ArrayList<>();
			for (BaseRemindTaskEntity baseRemindTaskEntity : baseRemindTaskEntityList) {
				String noticetype = baseRemindTaskEntity.getNoticetype();
				if (NoticeTypeEnum.App.equals(noticetype)) {
					baseRemindTaskEntityAppRemindList.add(baseRemindTaskEntity);
				}else if (NoticeTypeEnum.Email.equals(noticetype)) {
					baseRemindTaskEntityEmailRemindList.add(baseRemindTaskEntity);
				} else {
					continue;
				}
			}
			if (baseRemindTaskEntityAppRemindList.size() > 0) {
				this.insertMessageAppFromTask(baseRemindTaskEntityAppRemindList);
			}
			if (baseRemindTaskEntityEmailRemindList.size() > 0) {
				this.insertMessageEmailFromTask(baseRemindTaskEntityEmailRemindList);
			}
			Map<String, Object> map = new HashMap<>();
			map.put("paramvalue", timeNowString);
			// 更新RemindCheckConfigModifiedLastRunTime参数
			this.cboSysParamService.updateByWhere(map, "code='RemindCheckTaskLastRunTime'");
		} catch (Exception e) {
			Map<String, Object> map = new HashMap<>();
			map.put("paramvalue", timeNowString);
			// 更新RemindCheckConfigModifiedLastRunTime参数
			this.cboSysParamService.updateByWhere(map, "code='RemindCheckTaskLastRunTime'");
		}
	}

	/**
	 * @description: 进行app消息提醒
	 * @param baseRemindTaskEntityAppRemindList
	 * @author: maxiaodong
	 * @date: 2020年12月10日下午3:51:08
	 * @modify:
	 */
	private void insertMessageAppFromTask(List<BasicEntity> baseRemindTaskEntityAppRemindList) {
		List<Map<String, Object>> cboMessageAppMapList = new ArrayList<>();
		List<String> baseRemindTaskEntityIdList = new ArrayList<>();
		List<BasicEntity> cboMessageSysEntityList = new ArrayList<>();
		for (BasicEntity baseRemindTaskEntity : baseRemindTaskEntityAppRemindList) {
			String sourceid = ((BaseRemindTaskEntity) baseRemindTaskEntity).getSourceid();
			// MessageApp消息发送
			Map<String, Object> cboMessageAppMap = new HashMap<>();
			cboMessageAppMap.put(CboMessageAppEntity.FieldContent, ((BaseRemindTaskEntity) baseRemindTaskEntity).getContent());
			cboMessageAppMap.put(CboMessageAppEntity.FieldSourcetype, ((BaseRemindTaskEntity) baseRemindTaskEntity).getSourcetype());
			cboMessageAppMap.put(CboMessageAppEntity.FieldSourceid, sourceid);
			cboMessageAppMap.put(CboMessageAppEntity.FieldReceiverid, ((BaseRemindTaskEntity) baseRemindTaskEntity).getUserid());
			cboMessageAppMap.put("usercode", ((BaseRemindTaskEntity) baseRemindTaskEntity).getUsercode());
			cboMessageAppMap.put(CboMessageAppEntity.FieldSendtype, 0);
			cboMessageAppMap.put(CboMessageAppEntity.FieldExtendfield1, ((BaseRemindTaskEntity) baseRemindTaskEntity).getSubject());// 从task表改
			cboMessageAppMapList.add(cboMessageAppMap);
			baseRemindTaskEntityIdList.add(ConvertUtil.convertToString(baseRemindTaskEntity.getId()));
			// MessageSys消息发送
			CboMessageSysEntity cboMessageSysEntity = new CboMessageSysEntity();
			cboMessageSysEntity.setContent(((BaseRemindTaskEntity) baseRemindTaskEntity).getContent());
			cboMessageSysEntity.setSourcetype(((BaseRemindTaskEntity) baseRemindTaskEntity).getSourcetype());
			cboMessageSysEntity.setSourceid(ConvertUtil.convertToLong(sourceid));
			cboMessageSysEntity.setReceivercode(((BaseRemindTaskEntity) baseRemindTaskEntity).getUsercode());
			cboMessageSysEntity.setReceivername(((BaseRemindTaskEntity) baseRemindTaskEntity).getUsername());
			cboMessageSysEntity.setSubject(((BaseRemindTaskEntity) baseRemindTaskEntity).getSubject());
			cboMessageSysEntityList.add(cboMessageSysEntity);
		}
		// 每50条数据插一次，防止oa hessian超时
		int baseRemindTaskEntityAppRemindListSize = baseRemindTaskEntityAppRemindList.size();
		int lastIndex = 0;
		for (int i = 1; i <= baseRemindTaskEntityAppRemindListSize; i++) {
			if (i % 50 == 0 || i == (baseRemindTaskEntityAppRemindListSize)) {
				try {
					this.cboMessageAppService.insertList(cboMessageAppMapList.subList(lastIndex, i));
					this.cboMessageSysService.insertBatch(cboMessageSysEntityList.subList(lastIndex, i));
				} catch (Exception e) {
				} finally {
					this.baseRemindTaskService.updateExecute("update BASEREMINDTASK set state=1 where id in ("
							+ String.join(",", baseRemindTaskEntityIdList.subList(lastIndex, i)) + ")");
				}
				lastIndex = i;
			}
		}
	}

	/**
	 * @description: 进行email消息提醒
	 * @param baseRemindTaskEntityEmailRemindList
	 * @return void
	 * @author: wangxinhua
	 * @date: 2021/8/10 17:35
	 * @modify:
	 */
	private void insertMessageEmailFromTask(List<BasicEntity> baseRemindTaskEntityEmailRemindList) {
		List<BasicEntity> cboMessageEmailMapList = new ArrayList<BasicEntity>();
		List<String> baseRemindTaskEntityIdList = new ArrayList<>();
		for (BasicEntity baseRemindTaskEntity : baseRemindTaskEntityEmailRemindList) {
			String sourceid = ((BaseRemindTaskEntity) baseRemindTaskEntity).getSourceid();
			// MessageEmail发送
			CboMessageMailEntity cboMessageEmailMap = new CboMessageMailEntity();
			cboMessageEmailMap.setDisplayname(systemName);
			cboMessageEmailMap.setSubject(((BaseRemindTaskEntity) baseRemindTaskEntity).getSubject());
			cboMessageEmailMap.setContent(((BaseRemindTaskEntity) baseRemindTaskEntity).getContent()+((BaseRemindTaskEntity) baseRemindTaskEntity).getExtendcontent());
			cboMessageEmailMap.setSourceid(ConvertUtil.convertToLong(sourceid));
			cboMessageEmailMap.setSourcetype(((BaseRemindTaskEntity) baseRemindTaskEntity).getSourcetype());
			cboMessageEmailMap.setReceiverids(ConvertUtil.convertToString(((BaseRemindTaskEntity) baseRemindTaskEntity).getUserid()));
			cboMessageEmailMapList.add(cboMessageEmailMap);
			baseRemindTaskEntityIdList.add(ConvertUtil.convertToString(baseRemindTaskEntity.getId()));
		}
		// 每50条数据插一次，防止oa hessian超时
		int baseRemindTaskEntityAppRemindListSize = baseRemindTaskEntityEmailRemindList.size();
		int lastIndex = 0;
		for (int i = 1; i <= baseRemindTaskEntityAppRemindListSize; i++) {
			if (i % 50 == 0 || i == (baseRemindTaskEntityAppRemindListSize)) {
				try {
					this.cboMessageMailService.insertBatch(cboMessageEmailMapList.subList(lastIndex, i));
				} catch (Exception e) {
				} finally {
					this.baseRemindTaskService.updateExecute("update BASEREMINDTASK set state=1 where id in ("
							+ String.join(",", baseRemindTaskEntityIdList.subList(lastIndex, i)) + ")");
				}
				lastIndex = i;
			}
		}
	}
}
